<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
      <el-row class="cat_opt">
        <span>选择商品分类:</span>
        <!-- 选择商品分类的级联选择框 -->
        <el-cascader
          v-model="selectedOptionId"
          :options="cateList"
          :props="expandTrigger"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="activeDisbled" @click="addParams">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="activeMany" stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeHandle(scope.row,i)"
                >{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="activeDisbled" @click="addParams">添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table :data="activeOnly" stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeHandle(scope.row,i)"
                >{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数文本框 -->
      <el-dialog
        :title="'添加'+titleText"
        :visible.sync="addParamsVisible"
        width="30%"
        @close="addFormClose"
      >
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsSub">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数文本框 -->
      <el-dialog
        :title="'添加'+titleText"
        :visible.sync="editParamsVisible"
        width="30%"
        @close="editFormClose"
      >
        <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParamsSub">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 配置级联菜单中数据如何显示
      expandTrigger: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 用户在级联下拉菜单中选中的分类id
      selectedOptionId: [],
      // 动态的name名称
      activeName: 'many',
      // 动态参数的数据
      activeMany: [],
      // 静态参数的数据
      activeOnly: [],
      // 添加参数文本框
      addParamsVisible: false,
      // 添加属性数据验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      addForm: {
        attr_name: ''
      },
      // 修改参数文本框
      editParamsVisible: false,
      // 修改参数的数据验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      // 修改表单数据
      editForm: {}
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 如果按钮需要被禁用则返回true否则返回false
    activeDisbled() {
      if (this.selectedOptionId.length !== 3) {
        return true
      }
      return false
    },

    // 当前选中的三级分类的id
    cateId() {
      if (this.selectedOptionId.length === 3) {
        return this.selectedOptionId[2]
      }
      return null
    },
    // 动态添加文本框title文本
    titleText() {
      if (this.activeName == 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类列表失败')
      this.cateList = res.data
    },
    // 获取参数列表
    async getParamsList() {
      if (this.selectedOptionId.length !== 3) {
        this.selectedOptionId = []
        this.activeMany = []
        this.activeOnly = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$messaeg.error('获取失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        //控制按钮与文本框的显示与隐藏
        item.inputVisible = false
        // 输入文本框中输入的内容
        item.inputValue = ''
      })
      if (this.activeName == 'many') {
        this.activeMany = res.data
      } else {
        this.activeOnly = res.data
      }
    },
    // 级联选择框发生改变时触发的事件
    async handleChange() {
      this.getParamsList()
    },
    // Tab改时触发的事件
    handleTabClick() {
      this.getParamsList()
    },
    // 添加动态参数
    addParams() {
      this.addParamsVisible = true
    },
    // 重置表单
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 确定按钮发起请求
    addParamsSub() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_sel: this.activeName,
            attr_name: this.addForm.attr_name
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.getParamsList()
        this.addParamsVisible = false
      })
    },
    // 点击按钮 展示修改参数对话框
    async editParams(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { attr_sel: this.activeName }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.editForm = res.data

      this.editParamsVisible = true
    },
    // 关闭文本框重置修改表单
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定发起请求
    editParamsSub() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.getParamsList()
        this.editParamsVisible = false
      })
    },
    // 根据Id删除参数
    async delParams(attr_id) {
      const a = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (a !== 'confirm') return
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getParamsList()
    },
    // 点击按钮显示输入文本框
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      // $nextTick:在页面上元素被重新渲染之后，调用回调函数的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 回车或失去焦点触发事件 添加
    async handleInputConfirm(row) {
      // 判断输入的内容长度是否为0
      if (row.inputValue.trim().length === 0) {
        // 是则清输入框并隐藏，return出去
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 完成参数项的添加事件
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求，提交参数
      this.saveAttrVls(row)
    },
    async saveAttrVls(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    },
    async closeHandle(row, i) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVls(row)
    }
  }
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 10px;
}
.el-input {
  width: 120px;
}
</style>
